'use strict'

define(['jquery' , 'bootstrap' , 'select2' , 'shiftform' , 'validate' , 'validate.en',
        'editorConfig', 'editor', 'upload', 'zh',
        'uploader' , 'plupload' , 'qiniu'] , function($) {
  return {
    
    init: function(creditCouponBatchId) {
      
      this.initContentEdit();
      this.creditCouponBatchId = creditCouponBatchId;
      
    },
    
    initContentEdit: function() {
      var that = this;
      document.domain = window.__CTX__.rootDomain
      
      //实例化编辑器
      //建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
      var ue = UE.getEditor('editor', {
        autoHeightEnabled: false,
        autoFloatEnabled: true
      });

      // ajax 请求内容
      ue.addListener("ready", function () {
        $.ajax({
          type: 'GET',
          // 获取new content 的请求地址
          url:  window.__CTX__.root +  '/credit-coupon-batches/' + that.creditCouponBatchId + '/description',
          contentType:"application/json",
          success: function(data){ 
            ue.execCommand('inserthtml', data);
          },
          error: function(jqxhr) {
            // TODO add show error
            alert("请求数据失败");
          }
        })
      })
      
      $("form button[type='submit']").on('click', function(event) {
        event.preventDefault();
        /* Act on the event */
        if(UE.getEditor('editor').hasContents()) {
          
          var _form = $(this).parents('form');
          $.post( _form.attr('action'), _form.serialize(), function(data, textStatus, xhr) {
            
            var data = JSON.parse(data);
            
            if(data.code == 0) {
              // TODO 修改为目的跳转地址
              window.location.href = window.__CTX__.root  + "/credit-coupon-batches/" + that.creditCouponBatchId;
            } else {
              alert("" + data.message);
            }
          });
          
        }else {          
          UE.getEditor('editor').focus();
        }
      });
    },
    
  }
})